const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const watch = require('node-watch');

const proxyConfig = {
    context: ['/api/index.php', '/orgapi/index.php'],
    target: 'http://dev-rent.myscrm.cn:1002',
    secure: false,
    changeOrigin: true,
    cookieDomainRewrite: {
        "*": ""
    }
}

const proxyConfigFile = `${__dirname}/proxy.config.js`;
if (fs.existsSync(proxyConfigFile)) {
    let { router, pathRewrite } = require('./proxy.config');
    Object.assign(proxyConfig, {
        router(req) {
            return router(req)
        },
        pathRewrite(apiPath, req) {
            return pathRewrite(apiPath, req)
        }
    });
    watch(proxyConfigFile, () => {
        console.info('proxy setting changed')
        const content = fs.readFileSync(proxyConfigFile, 'utf-8')
        const object = eval(content);
        router = object.router;
        pathRewrite = object.pathRewrite;
    })
}

module.exports = {
    dll: {
        debug: true,
        version: 1,
        plugins: [
            new webpack.ContextReplacementPlugin(/[/\\]locale/, './locale/', /zh-cn/)
        ],
        entry: {
            vendor: [
                './public/js/jquery',
                'angular',
                'es6-promise',
                'underscore',
                './public/js/lodash',
            ],
            select2: [
                'select2'
            ],
            highcharts: [
                'highcharts'
            ],
            moment: [
                'moment'
            ],
            jqGrid: [
                './public/misc/jquery.jqGrid-4.6.0/js/i18n/grid.locale-cn',
                './public/misc/jquery.jqGrid-4.6.0/js/jquery.jqGrid.min'
            ],
            ueditor: [
                './public/js/ueditor'
            ],
            mediaUpload: [
                './public/misc/mediaUpload/js/jquery.form',
                './public/misc/mediaUpload/js/myUpload'
            ]
        }
    },
    module: {
        rules: [
            {
                test: /angular\.min\.js/,
                use: ['expose-loader?angular'],
            },
            {
                test: /WdatePicker\.js/,
                use: [
                    { loader: 'expose-loader?WdatePicker' },
                    { loader: 'exports?WdatePicker' }
                ]
            },
            {
                test: /underscore-min\.js/,
                use: ['expose-loader?_'],
            },
            {
                test: /md5\.min\.js/,
                use: ['expose-loader?md5'],
            },
            {
                test: /\.js$/,
                exclude: [
                    /node_modules[\\/](?!@yunke)/,
                    /WdatePicker\.js/,
                    /md5\.min\.js/,
                    /plupload\.min\.js/,
                    /moxie\.min\.js/,
                    /angular\.min\.js/,
                    /moment\.min\.js/
                ],
            },
            {
                test: /\.s?html$/,
                oneOf: [
                    {
                        resourceQuery: /url/, // foo.html?url
                        use: [
                            {
                                loader: 'file-loader',
                                options: {
                                    name: '[path][name].[hash].[ext]'
                                }
                            },
                            {
                                loader: 'extract-loader'
                            },
                            {
                                loader: 'html-loader',
                                options: {
                                    interpolate: true,
                                }
                            }
                        ]
                    },
                    {
                        use: [
                            {
                                loader: 'html-loader',
                                options: {
                                    interpolate: true,
                                }
                            }
                        ]
                    }
                ]
            },
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            {
                from: '{*.?(s)html,!(node_modules|dist)/**/*.?(s)html}'
            },
            {
                from: 'favicon.ico'
            }
        ])
    ],
    resolve: {
        alias: {
            "myservice": path.join(__dirname, "public/js/myservice/"),
            "plugins": path.join(__dirname, "public/js/plugins/"),
            "jquery": path.join(__dirname, "public/js/jquery"),

            "angular-ui": path.join(__dirname, "public/js/plugins/angular-ui"),
            "webuploader": path.join(__dirname, "public/js/lib/webuploader/webuploader.min"),
            "introjs": path.join(__dirname, "public/js/plugins/introjs/intro.min"),
            "dropdownlist": path.join(__dirname, "public/js/plugins/dropdownlist/dropdownlist.min"),
            "uploader": path.join(__dirname, "public/js/plugins/uploader/jquery.fileupload.min"),
            "select": path.join(__dirname, "public/js/plugins/select/select"),
            "authorize": path.join(__dirname, "/public/js/myservice/authorize"),
            "side": path.join(__dirname, "/public/js/myservice/side"),
            "ui-router": path.join(__dirname, "public/js/lib/angular/angular-ui-router.min"),
            "dragdrop": path.join(__dirname, "public/js/lib/angular/angular-dragdrop"),
            "apiService": path.join(__dirname, "public/js/apiService"),

            "mypublic": path.join(__dirname, "mypublic"),
        }
    },
    devServer: {
        proxy: [proxyConfig]
    },
    parserConfig: {
        otherEntry: ['./public/js/permission', './public/js/angularGlobal'],
        htmlWebpackPluginChunks: (key) => {
            return /^(cms|official)\//.test(key) ? ['commons', 'jqueryUiThemes'] : ['commons']
        },
        plugins: (entry) => {
            return [
                new webpack.optimize.CommonsChunkPlugin({
                    name: "commons",
                    minChunks: (module, count) => {
                        return module.resource && !(/\/jquery-ui-themes-1.11.2\//).test(module.resource) && count >= 3;
                    },
                    chunks: Object.keys(entry)
                }),
                new webpack.optimize.CommonsChunkPlugin({
                    name: "jqueryUiThemes",
                    minChunks: (module, count) => {
                        return module.resource && (/\/jquery-ui-themes-1.11.2\//).test(module.resource) && count >= 3;
                    },
                    chunks: Object.keys(entry)
                })
            ]
        }
    }
}
